package com.jcl.vertx.router;

import com.jcl.vertx.BaseRouter;
import io.vertx.core.Future;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

/**
 * 简单的api调用案例
 */
public class RouterSample extends BaseRouter {

    @Override
    public void start(Future<Void> startFuture) throws Exception {

        //这个我没有走通，看不懂~
        // EventBus eb = vertx.eventBus();
        // eb.consumer("http://localhost:8888/", message -> {
        //     System.out.println("I have received a message: " + message.body());
        // });

        router = Router.router(vertx);
        router.route("/").handler(ctx -> {
            System.out.println("/");
            ctx.response().putHeader("content-type", "application/json").end(new JsonObject().put("name", "haijia").toString());
        });

        //经典模式
        router.post("/test").handler(req -> {
            System.out.println("/test");
            String page = req.request().getParam("page");
            req.response().putHeader("content-type", "application/json").end(new JsonObject().put("page", page).toString());
        });

        //REST模式
        router.post("/test/:page/:age").handler(req -> {
            String page = req.request().getParam("page");
            String age = req.request().getParam("age");
            req.response().putHeader("content-type", "application/json").end(new JsonObject().put("page", page).put("age", age).toString());
        });

        router.route().handler(BodyHandler.create());

        //如果获取form-data格式
        router.route("/test").handler(req -> {
            String page = req.request().getFormAttribute("page");
            req.response().putHeader("content-type", "application/json").end(new JsonObject().put("page1", page).toString());
        });

        vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
            if (http.succeeded()) {
                startFuture.complete();
                System.out.println("HTTP server started on port 8888");
            } else {
                startFuture.fail(http.cause());
            }
        });
    }
}
